﻿-- =============================================
-- Author:		David Settino
-- Create date: 01/03/2011
-- Modified:  Brian Wilkins
-- Modify date: 07/25/2014
-- Description:	Converts a circle represented as
--    a string containing lat, lon, and radius
--    to a geographic data type
-- =============================================

CREATE FUNCTION [dbo].[CircleToGeography](@circle varchar(500))
RETURNS geography
AS
BEGIN
  DECLARE @index int
  DECLARE @pointstr VARCHAR(50)
  DECLARE @latstr VARCHAR(50)
  DECLARE @lonstr VARCHAR(50)
  DECLARE @radius decimal(18,6)
  DECLARE @lat decimal(18,6)
  DECLARE @lon decimal(18,6)
  DECLARE @Polygon [geography]
  SET @index = CHARINDEX(' ', @Circle)
  SET @radius = SUBSTRING(@Circle, @index+1, LEN(@Circle)-@index)
  SET @pointstr = SUBSTRING(@Circle, 0, @index)
  SET @radius = @radius * 1000
  SET @index = CHARINDEX(',', @pointstr)
  SET @latstr = SUBSTRING(@pointstr,0, @index)
  SET @lonstr = SUBSTRING(@pointstr, @index+1, LEN(@pointstr)-@index)
  SET @lat = CAST(@latstr AS DECIMAL(18,6))
  SET @lon = CAST(@lonstr AS DECIMAL(18,6))
  SET @Polygon = geography::Point(@Lat,@Lon,4326).STBuffer(@Radius)
  RETURN @Polygon
END